﻿using Common.Contract.Authentication.Record;
using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request;
using Common.Contract.Customer.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Service.Command;
using Customer.Model.Interface;
using Customer.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Customer.Core.ServiceCommand
{
    public class RetrieveCustomerRepresentativeCelebrationServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveCustomerRepresentativeCelebrationRequest, RetrieveCustomerRepresentativeCelebrationResponse>
    {
        #region Properties
        public UserRecord Dao;
        public FilterRecord TextSearch;
        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        #endregion
        public RetrieveCustomerRepresentativeCelebrationServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveCustomerRepresentativeCelebrationRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.CurrentUser == null)
            {
                throw new ArgumentException("MSBO Dao must be set", "request");
            }
            else
            {
                Dao = Request.CurrentUser;
            }
            TextSearch = Request.Filter;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
        }

        protected override bool OnExecute(RetrieveCustomerRepresentativeCelebrationResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            try
            {
                List<CustomerRepresentativeRecord> records = new List<CustomerRepresentativeRecord>();
                List<Customers> listCustomer = Providers.Customers.RetrieveCustomerByDao(out totalRecord, Dao, TextSearch);
                List<CustomerRelation> listCustomerRelation = Providers.CustomerAlerts.RetrieveAllCustomerRelation(Dao, TextSearch);
                Dictionary<string, Branch> listBranches = Providers.Branchs.RetrieveAllBranches().ToDictionary(x => x.BranchId);
                if (listCustomer != null && listCustomerRelation != null && listCustomer.Count > 0 && listCustomerRelation.Count > 0)
                {

                    var result = (from x in listCustomer
                                  join y in listCustomerRelation on x.Cif equals y.Cif
                                  select new CustomerRepresentativeRecord
                                  {
                                      Zone = listBranches.ContainsKey(x.BranchId) ? listBranches[x.BranchId].Region : string.Empty,
                                      DaoName = x.DaoName,
                                      Dao = x.Dao,
                                      Branch = listBranches.ContainsKey(x.BranchId) ? listBranches[x.BranchId].BranchNameSme : string.Empty,
                                      Cif = x.Cif,
                                      CustName = x.CusName,
                                      RepresentativeName = y.CusRelName,
                                      EmailAddress = string.IsNullOrEmpty(y.EmailRelCus) ? string.Empty : y.EmailRelCus,
                                      Mobile = string.IsNullOrEmpty(y.MobileRelation) ? string.Empty : y.MobileRelation,
                                      CelebrationDate = y.BirOfRelCust.Value,
                                      Position = y.CusRelPos
                                  });
                    result = result.OrderBy(x => x.Zone).ThenBy(x => x.Branch).ThenBy(x => x.DaoName);
                    records = result.Skip(pageIndex * pageSize).Take(pageSize).ToList();
                    response.Page = new PageRecord
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalRecords = result.Count()
                    };
                }
                else
                {
                    response.Page = new PageRecord
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalRecords = 0
                    };
                }
                response.Records = records;
            }
            catch (Exception e)
            {
                isSuccess = false;
                errorMessage = e.Message;
            }
            response.ErrorMessage = errorMessage;
            return isSuccess;
        }
    }
}
